from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from myapp.models import Movie, Actor


class IndexView(View):
    def get(self, request):
        return render(request, 'index.html')


class MovieListView(View):
    def get(self, request):
        # 根据上映时间排序, 取出所有的电影
        # movies = Movie.objects.order_by('-play_date')[:5]  # 取前五个
        movies = Movie.objects.order_by('-play_date')
        return render(request, 'movie_list.html', locals())


class ActorListView(View):
    def get(self, request):
        actors = Actor.objects.order_by('-movie_count')
        return render(request, 'actor_list.html', locals())


class MovieAddview(View):
    def get(self, request):
        return render(request, 'movie_add.html')

    def post(self, requset):
        movie_title = requset.POST.get('movie_title')  # 电影标题
        movie_img = requset.FILES.get('movie_img')  # 文件内容
        movie = Movie(title=movie_title, img=movie_img)
        movie.save()

        return HttpResponse('上传成功')


class ActorAddView(View):
    def get(self, request):
        movies = Movie.objects.all()
        return render(request, 'actor_add.html', locals())

    def post(self, request):
        actor_name = request.POST.get('actor_name')
        actor_age = request.POST.get('actor_age')
        actor_gender = request.POST.get('actor_gender')
        movie_list = request.POST.getlist('movie_list')
        actor = Actor(
            name=actor_name,
            age=actor_age,
            gender=actor_gender,
            movie_count=len(movie_list)
        )
        actor.save()
        for movie in movie_list:
            actor.movie_set.add(movie)
        actor.save()
        return HttpResponse('添加成功!')


class ActorView(View):
    def get(self, request):
        actor_id = request.GET.get('id')
        actor = Actor.objects.get(id=actor_id)
        movies = actor.movie_set.all()
        return render(request, 'actor.html', locals())


class MovieView(View):
    def get(self, request):
        # 展示电影详情
        # 取电影id
        movie_id = request.GET.get('id')
        movie = Movie.objects.get(id=movie_id)
        # 根据电影取到演员
        actors = movie.actor.all().order_by('age')

        return render(request, 'movie.html', locals())
